package com.isesol.ime.service.mq.consumer;

import com.alibaba.rocketmq.client.consumer.listener.*;
import com.alibaba.rocketmq.client.exception.*;
import com.isesol.arch.common.mq.*;
import com.isesol.ime.service.*;
import com.isesol.ime.service.mq.topic.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import java.io.*;
import java.util.*;

/**
 * 下指令
 */
@Component
public class SendOrderConsumer extends BaseConsumer{

	@Resource
	SendOrderService sendOrderService;

	@Override
	public Class<? extends Topic> getTopic(){

		return SendOrderTopic.class;
	}

	@Override
	public void doLogErrorConsumeMessage(MsgObj msgObj){

		logger.info("SendOrderConsumer doLogErrorConsumeMessage");

	}

	@Override
	public ConsumeConcurrentlyStatus doConsumeMessage(final MsgObj msgObj){

		ConsumeConcurrentlyStatus consumeConcurrentlyStatus = ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

		try{

			List<Serializable> msgs = msgObj.getMsgList();

			for (final Serializable obj : msgs){

				if (obj instanceof String){

					logger.info("SendOrder Consumer body={}", obj);

					sendOrderService.sendOrder((String) obj);
				}
			}
		} catch (Exception e){

			logger.error("SendOrderConsumer error", e);

			if (msgObj.getReConsumeTimes() >= maxRetryCount){

				logger.error("SendOrder reConsumeTimes >" + maxRetryCount + ",msgs:" + msgObj + ",context:" + msgObj.getContext());

				msgObj.setErrorMsg(e.getMessage());
				doLogErrorConsumeMessage(msgObj);

				return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

			} else{

				return ConsumeConcurrentlyStatus.RECONSUME_LATER;
			}
		}

		return consumeConcurrentlyStatus;
	}

	@PostConstruct
	public void init() throws MQClientException{

		super.init();

		logger.info("【MQ SEND-ORDER consumer init 】,messageModel={}", getMessageModel());

	}

	@PreDestroy
	public void destroy(){

		super.destroy();
	}
}
